//导入数据库
const { products, Op } = require('../Model');

let fn_data = async(ctx, next) => {
    let keyword = ctx.request.query.keyword
    if (keyword) {
        ctx.body = await products.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? -1 : keyword },
                    { name: keyword },
                    { price: keyword },
                    { stock: keyword }
                ]
            }
        })
    } else {
        ctx.body = await products.findAll({
            order: [
                ['id', 'asc']
            ]
        });
    }
}


//添加数据
let fn_addorEndit = async(ctx, next) => {
    let obj = ctx.request.body;
    let tempobj = {};
    tempobj.name = obj.name;
    tempobj.price = obj.price;
    //判断save引发的请求到底是新增还是编辑
    if (!obj.id) {
        //已存在相同名称的不可以添加  
        let arr = await products.findAll();
        let temp = arr.filter(item => {
            console.log(item);
            console.log(item.name);
            return item.name == obj.name;
        })
        if (temp.length === 0) {
            console.log(tempobj);
            await products.bulkCreate([
                tempobj
            ]);
            ctx.body = {
                code: 200,
                data: tempobj,
                msg: "添加成功"
            }
        } else {
            ctx.body = {
                code: 404,
                data: null,
                msg: "添加失败"
            }
        }
    } else {
        await products.update({ name: obj.name, price: obj.price }, { where: { id: obj.id } });
        ctx.body = {
            code: 1000,
        }
        await products.findAll();

    }
}

//得到修改的数据
let fn_endit = async(ctx, next) => {
    ctx.body = await products.findAll({
        where: {
            id: parseInt(ctx.request.params.id)
        }
    })
}

//删除数据
let fn_delete = async(ctx, next) => {
    let id = ctx.request.params.id
    await products.destroy({
        where: {
            id: id
        }
    })

    ctx.body = await products.findAll({
        order: [
            ['id', 'asc']
        ]
    });
}

module.exports = {
    //展示数据或查找
    'get /produce': fn_data,
    //新增
    'post /produce': fn_addorEndit,
    //修改
    'get /produce/:id': fn_endit,
    'put /produce': fn_addorEndit,
    //删除  
    'delete /produce/:id': fn_delete
}